﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

using Groupon.Net;

public partial class _Default : System.Web.UI.Page
{
    private static string _selectedDivisionId;

    protected void Page_Load(object sender, EventArgs e)
    {
        Client.ClientID = "";
        Client.ForceSuccessResponse = true;
        Client.ClientException += new EventHandler<ClientExceptionEventArgs>(Client_ClientException);
               
        this.dealsRepeater.ItemCreated += new RepeaterItemEventHandler(dealsRepeater_ItemCreated);
        this.dealsRepeater.ItemCommand += new RepeaterCommandEventHandler(dealsRepeater_ItemCommand);
        this.divisionList.SelectedIndexChanged += new EventHandler(divisionList_SelectedIndexChanged);

        if (!Page.IsPostBack)
        {
            this.BindDivisions();
            this.BindDeals();

            if (divisionList.Items.Count > 0)
            {
                _selectedDivisionId = divisionList.Items[0].Value;
            }

            if (Deals.Count > 0)
            {
                this.BindDeal(Deals[0]);
            }
        }
    }

    void divisionList_SelectedIndexChanged(object sender, EventArgs e)
    {
        _selectedDivisionId = divisionList.Items[divisionList.SelectedIndex].Value;

        BindDeals();
        if (Deals.Count > 0)
        {
            this.BindDeal(Deals[0]);
        }
    }

    private static List<Deal> Deals
    {
        get
        {
            List<Deal> result = HttpRuntime.Cache["Deals" + _selectedDivisionId] as List<Deal>;
            if (result== null)
            {
                result = CacheDeals(_selectedDivisionId);
            }
            return result;

        }
    }

    private static List<Division> Divisions
    {
        get
        {
            List<Division> result = HttpRuntime.Cache["Divisions"] as List<Division>;
            if (result == null)
            {
                result = CacheDivisions();
            }
            return result;

        }
    }

    private static List<Division> CacheDivisions()
    {
        List<Division> result = Client.GetDivisions();

        HttpRuntime.Cache.Insert(
           "Division",
           result,
           null,
           Cache.NoAbsoluteExpiration,
           new TimeSpan(0, 0, 15),
           CacheItemPriority.Default,
           new CacheItemRemovedCallback(RemovedCallback));

        return result;
    }

    private static List<Deal> CacheDeals(string divisionId)
    {
        List<Deal> result = Client.GetDeals(divisionId);

        HttpRuntime.Cache.Insert(
           "Deals" + divisionId,
           result,
           null,
           Cache.NoAbsoluteExpiration,
           new TimeSpan(0, 0, 15),
           CacheItemPriority.Default,
           new CacheItemRemovedCallback(RemovedCallback));

        return result;

    }

    public static void RemovedCallback(String key, object value, CacheItemRemovedReason removedReason) { }
    
    void dealsRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) 
    {
        string dealId = e.CommandArgument.ToString();

        switch (e.CommandName)
        {
            case "View":
                Deal deal = (from Deal d in Deals where d.Id.Equals(dealId) select d).FirstOrDefault();
                BindDeal(deal);
                BindDeals();
                BindDivisions();
                break;
            default: break;
        }
    }

    void dealsRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Deal deal = (Deal)e.Item.DataItem;
            if (deal != null)
            {
                ((Image)e.Item.FindControl("smallImage")).ImageUrl = deal.SmallImageUrl;
                ((Label)e.Item.FindControl("titleLabel")).Text = deal.Title;
                ((HyperLink)e.Item.FindControl("moreInfoLink")).NavigateUrl = Client.GetCommissionJunctionUrl("5244473", deal.DealURL);

            }
        }
    }

    void BindDivisions()
    {
        this.divisionList.DataSource = Divisions;
        this.divisionList.DataTextField = "Name";
        this.divisionList.DataValueField = "Id";
        this.divisionList.DataBind();
    }

    void BindDeals()
    {
        this.dealsRepeater.DataSource = Deals;
        this.dealsRepeater.DataBind();
    }

    void BindDeal(Deal deal)
    {
        if (deal != null)
        {
            this.titleLabel.Text = deal.Title;
            this.pitchLiteral.Text = deal.PitchHTML;
            this.smallImage.ImageUrl = deal.LargeImageURL;
            if (deal.Merchants.Count > 0)
            {
                this.merchantWebsite.NavigateUrl = deal.Merchants[0].Website;
                this.merchantWebsite.Text = deal.Merchants[0].Name;
            }

            this.optionsRepeater.DataSource = deal.Options;
            this.optionsRepeater.DataBind();
        }
    }

    void Client_ClientException(object sender, ClientExceptionEventArgs e)
    {
        string message = string.Concat(e.Messages.ToArray());

        Response.Write(string.Format("<span style='color:red;'>{0}</span>", message));
    }
}